package com.chrissy.music.framework.service;

import com.chrissy.music.common.cache.RedisCache;
import com.chrissy.music.common.constant.CacheConstants;
import com.chrissy.music.common.context.AuthenticationContextHolder;
import com.chrissy.music.common.entity.SysUser;
import com.chrissy.music.framework.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 登录密码方法
 *
 * @author ruoyi
 */
@Component
@RequiredArgsConstructor
public class SysPasswordService {

    private final RedisCache redisCache;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validate(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        if (!matches(user, password)) {
            redisCache.set(getCacheKey(username), lockTime, 300);
        } else {
            clearLoginRecordCache(username);
        }
    }

    public boolean matches(SysUser user, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        if (Boolean.TRUE.equals(redisCache.hasKey(getCacheKey(loginName)))) {
            redisCache.delete(getCacheKey(loginName));
        }
    }
}
